package cn.zmwh.im.server.modules.ums.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.im.common.enums.IMTerminalType;
import cn.zmwh.im.common.pojo.dto.IMUserInfo;
import cn.zmwh.im.server.constant.IMRedisKey;
import cn.zmwh.im.server.exception.RRException;
import cn.zmwh.im.server.modules.ums.mapper.ImUserMapper;
import cn.zmwh.im.server.modules.ums.pojo.dto.MessageDB;
import cn.zmwh.im.server.modules.ums.pojo.entity.ImUser;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-06-19
 */
@Service
public class ImUserService extends ServiceImpl<ImUserMapper, ImUser> {

    @Autowired
    private RedisTemplate redisTemplate;

    public Set<MessageDB> qryMessageDb(Set<Long> userIds) {

        Set<MessageDB> dbUserIds = new HashSet<>();

        if (CollUtil.isEmpty(userIds)) {
            return dbUserIds;
        }
        List<ImUser> dpDbIndexEntities = baseMapper.selectByIds(userIds);
        if (CollUtil.isEmpty(dpDbIndexEntities)) {
            throw new RRException("数据库路由不存在！");
        }
        String separator = ":";
        Map<String, List<ImUser>> collect = dpDbIndexEntities.stream().collect(Collectors.groupingBy(item -> item.getMessageDb() + separator + item.getMessageTable()));
        for (String key : collect.keySet()) {
            List<ImUser> dpDbIndexEntitiesItem = collect.get(key);
            Set<Long> dpAccountIdsByDbIndex = dpDbIndexEntitiesItem.stream().map(ImUser::getId).collect(Collectors.toSet());
            MessageDB dbDTO = new MessageDB();
            String[] split = key.split(separator);
            dbDTO.setDb(Integer.valueOf(split[0]));
            dbDTO.setTable(Integer.valueOf(split[1]));
            dbDTO.setUserIds(dpAccountIdsByDbIndex);
            dbUserIds.add(dbDTO);
        }
        return dbUserIds;
    }

    /**
     * 根据用户获取在线的用户
     *
     * @param ids
     * @return
     */
    public List<IMUserInfo> uidToOnline(Set<Long> ids) {
        Map<String, IMUserInfo> receiverMap = new HashMap<>();
        for (Long uid : ids) {
            IMTerminalType[] values = IMTerminalType.values();
            for (IMTerminalType value : values) {
                String terminalV = value.terminal();
                String key = StrUtil.join(":", IMRedisKey.GAIN_SERVER_ID, uid, terminalV);
                receiverMap.put(key, new IMUserInfo(uid, terminalV));
            }
        }

        List<IMUserInfo> list = new ArrayList<>();
        List<Object> serverIds = redisTemplate.opsForValue().multiGet(receiverMap.keySet());
        int index = 0;
        for (Map.Entry<String, IMUserInfo> entry : receiverMap.entrySet()) {
            Object serverId = serverIds.get(index++);//index++后置递增， ++index前置递增
            if (serverId == null) {
                continue;
            }
            IMUserInfo value = entry.getValue();
            value.setServerId(serverId.toString());
            list.add(value);
        }
        return list;
    }
}
